package com.tt1000.settlementplatform.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.zxing.ReaderException;
import com.tt1000.settlementplatform.MainActivity;
import com.tt1000.settlementplatform.R;
import com.tt1000.settlementplatform.app.MyApplication;
import com.tt1000.settlementplatform.base.BaseFragment;
import com.tt1000.settlementplatform.bean.MemberResultBean;
import com.tt1000.settlementplatform.bean.member.DaoSession;
import com.tt1000.settlementplatform.bean.member.StoreConfig;
import com.tt1000.settlementplatform.bean.member.SyncResultInfo;
import com.tt1000.settlementplatform.bean.member.TfCardInfo;
import com.tt1000.settlementplatform.bean.member.TfConsumeCardRecord;
import com.tt1000.settlementplatform.bean.member.TfConsumeCardRecordDao;
import com.tt1000.settlementplatform.bean.member.TfConsumeDetailsRecord;
import com.tt1000.settlementplatform.bean.member.TfConsumeOrderRecord;
import com.tt1000.settlementplatform.bean.member.TfMealTimes;
import com.tt1000.settlementplatform.bean.member.TfMealTimesDao;
import com.tt1000.settlementplatform.bean.member.TfMemberAccountRecord;
import com.tt1000.settlementplatform.bean.member.TfMemberInfo;
import com.tt1000.settlementplatform.bean.result_info.OnlineUpdateResultInfo;
import com.tt1000.settlementplatform.bean.result_info.UpdateResultInfo;
import com.tt1000.settlementplatform.feature.network.LocalRetrofit;
import com.tt1000.settlementplatform.utils.MyConstant;
import com.tt1000.settlementplatform.utils.MyUtil;
import com.tt1000.settlementplatform.zxing.android.CaptureActivity;

import org.json.JSONException;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observer;
import rx.schedulers.Schedulers;

import static android.app.Activity.RESULT_OK;
import static com.tt1000.settlementplatform.utils.MyConstant.TAG;
import static com.tt1000.settlementplatform.utils.MyConstant.gSharedPre;
import static com.tt1000.settlementplatform.utils.MyUtil.getPrimaryValue;

public class BusSettlementFragment extends BaseFragment implements View.OnClickListener {
    private Button bus_num0, bus_num1, bus_num2, bus_num3, bus_num4, bus_num5, bus_num6, bus_num7, bus_num8, bus_num9, bus_num_dot;
    private ImageButton bus_refresh, bus_scan, bus_enter;
    private TextView bus_status, bus_money;
    private EditText bus_put_price;
    private static final int SETTLEMENT = 777;
    // 当前小票编号，在生成订单后被赋值
    private static String curOrderNo = "";
    private String payMsg = "";
    private MediaPlayer mPlayer;
    private String cardId;
    private boolean isPlay = false;
    private String code = "";
    // 账户余额
    private float accoutBalance;
    private static final int REQUEST_CODE_SCAN = 0x0000;
    private static final String DECODED_CONTENT_KEY = "codedContent";

    private boolean fixed_price_status;

    @Override
    protected int setContentView() {
        return R.layout.bus_settlement_fragment;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initview();
//        initTimer();
    }

    public ScheduledExecutorService mExecutor = new ScheduledThreadPoolExecutor(4);

    private void initTimer() {
        mExecutor.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                try {
                    payResultSelect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 0, 1, TimeUnit.SECONDS);
    }

    private void payResultSelect() {

    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SETTLEMENT:
                    try {
                        curOrderNo = MyUtil.getPrimaryValue();
                        if (fixed_price_status && !"0".equals(bus_money.getText().toString())) {
                            payMsg = MyConstant.gFormat.format(Float.parseFloat(bus_money.getText().toString().trim()));
                            if (payMsg.length() > 9) {
                                showPayStatus("金额超过限制");
                                payMsg = "";
                                return;
                            }
                            bus_put_price.setText("");
                            playVoice(MyConstant.SP_MEDIA_PLEASE_SET_CARD);
                            showPayStatus("请刷卡");
                        } else {
                            String num = bus_put_price.getText().toString().trim();
                            if (!MyUtil.isNumber(num)) {
                                refresh();
                                return;
                            }
                            payMsg = MyConstant.gFormat.format(Float.parseFloat(num));
                            if (!"0".equals(bus_money.getText().toString()) && "请刷卡".equals(bus_status.getText().toString())) {
                                String price = bus_money.getText().toString().trim();
                                float v = Float.parseFloat(price);
                                float v1 = Float.parseFloat(payMsg);
                                payMsg = MyConstant.gFormat.format(v + v1);
                                if (!MyUtil.isNumber(payMsg)) {
                                    refresh();
                                    return;
                                }
                            }
                            if (payMsg.length() > 9) {
                                showPayStatus("金额超过限制");
                                payMsg = "";
                                return;
                            }
                            bus_put_price.setText("");
                            bus_money.setText(payMsg);
                            playVoice(MyConstant.SP_MEDIA_PLEASE_SET_CARD);
                            showPayStatus("请刷卡");
                        }
                    } catch (Exception e) {
                        Log.e("frost_handle_settlement", e.getMessage());
                    }
                    break;
            }
        }
    };

    private void goScan() {
        Intent intent = new Intent(mContext, CaptureActivity.class);
        startActivityForResult(intent, REQUEST_CODE_SCAN);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                //返回的文本内容
                String content = data.getStringExtra(DECODED_CONTENT_KEY);
                if (code.equals(content)){
                    showPayStatus("请刷新二维码");
                    return;
                }
                code = content;
                //返回的BitMap图像
                bus_put_price.setText(content);
                bus_put_price.setText("");
                if (content.substring(0, 2).equals("56") && content.length() == 22) {
                    getMemberCardBalance(content);
                } else {
                    showPayStatus("暂不支持该方式支付");
                }
            }
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        ((MainActivity) context).setScanCallback(new MainActivity.OnScanResultCallback() {

            @Override
            public void onresult(int requestCode, int resultCode, Intent data) {

            }

            @Override
            public void onNewIntent(Intent intent) {
                try {
                    Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                    // 能获取到卡号，且未支付
                    if (tag != null && tag.getId() != null) {
                        String smartCardId = MyUtil.ByteArrayToHexString(tag.getId());
                        if (TextUtils.isEmpty(smartCardId)) {
                            showPayStatus("非法卡");
                            playVoice(MyConstant.SP_MEDIA_ILLEGAL_CARD);
                        } else {
                            long convertId = MyUtil.computeMemberId(smartCardId);
                            if (convertId == 0) {
                                showPayStatus("非法卡");
                                playVoice(MyConstant.SP_MEDIA_ILLEGAL_CARD);
                                return;
                            }
                            int diff = 10 - String.valueOf(convertId).length();
                            cardId = String.valueOf(convertId);
                            // 不足10位补0
                            if (diff >= 0) {
                                for (int i = 0; i < diff; i++) {
                                    cardId = ("0" + cardId);
                                }
                                /**
                                 * 测试的时候使用
                                 * 正常卡：1852084081
                                 * 挂失卡：1852084082
                                 * 注销卡：1852084083
                                 * 会员注销卡：1852084084
                                 */
                                // 最终得到去数据库查询的IC_ID
                                getMemberCardBalance(String.valueOf(cardId));
                            } else if (diff < 0) {
                                showMessage("会员卡", "非法卡");
                                playVoice(MyConstant.SP_MEDIA_ILLEGAL_CARD);
                                return;
                            }
                        }
                    }
                } catch (Exception e) {
                    Log.e("frost_pay_card", e.getMessage());
                }
            }
        });
    }

    private void getMemberCardBalance(final String icId) {
        if (isPlay){
            return;
        }
        Log.e("frost", "----------" + icId);
        try {
            if (!MyUtil.obtainNetworkStatus(mContext)) {
                showPayStatus("当前无网络连接");
                return;
            }
            if (!TextUtils.isEmpty(payMsg)) {
                showPayStatus("支付中...");
            }
            isPlay = true;
            String ip = gSharedPre.getString(MyConstant.SP_Server_IP, "");
            String port = gSharedPre.getString(MyConstant.SP_Server_PORT, "");
            String clienCode, storeCode;
            try {
                clienCode = mainActivity.pUserInfo.getCLIENT_CODE();
                storeCode = mainActivity.pUserInfo.getSTORE_CODE();
            } catch (Exception e) {
                clienCode = gSharedPre.getString(MyConstant.CLIENT_CODE, "");
                storeCode = gSharedPre.getString(MyConstant.STORE_CODE, "");
            }
            String url = "http://" + ip + ":" + port + "/k-occ/member/info/" + clienCode + "/" + storeCode + "/icId/" + icId;
            Log.e("frost", "url----" + url);
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .build();
            final Request request = new Request.Builder()
                    .url(url)
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    isPlay = false;
                    showPayStatus("支付错误，请重试");
                    Log.e("frost_geticresult",e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Gson gson = new Gson();
                    String body = response.body().string();
                    try {
                        if (!TextUtils.isEmpty(body)) {
                            Log.e("frost", body);
                        }
                        MemberResultBean memberResultBean = gson.fromJson(body, MemberResultBean.class);
                        if (memberResultBean.isResult()) {
                            String balance = memberResultBean.getData().getBalance();
                            String staffNumber = memberResultBean.getData().getStaffNumber();
                            calcurlateMemberBalance(icId, balance, staffNumber);
                        } else {
                            showPayStatus(memberResultBean.getMsg());
                            isPlay = false;
                        }
                    } catch (Exception e) {
                        isPlay = false;
                        if (!TextUtils.isEmpty(payMsg)) {
                            showPayStatus("支付错误，请重试");
                        }
//                        FailResultBean failResultBean = gson.fromJson(body, FailResultBean.class);
//                        if (!failResultBean.isResult()){
//                            showPayStatus(failResultBean.getMsg());
//                        }
                        Log.e("frost_getmember", e.getMessage());
                    }
                }
            });
        } catch (Exception e) {
            isPlay = false;
            showPayStatus("支付错误，请重试");
            Log.e("frost_getmember", e.getMessage());
        }
    }

    public void calcurlateMemberBalance(String icId, String balance, String staffNumber) {
        try {
            if (!TextUtils.isEmpty(icId) && !TextUtils.isEmpty(balance)) {
                float payNum = Float.parseFloat(payMsg);
                float record = Float.parseFloat(balance) - payNum;
                if (record < 0) {
                    showPayStatus("余额不足");
                    isPlay = false;
                    payMsg = "";
                    playVoice(MyConstant.SP_MEDIA_MONEY_NOT_ENOUGH);
                    return;
                } else {
                    createConsumeInfo(payNum, record, staffNumber, "1", icId, 1 + "", 1, 1);
                }
            }
        } catch (Exception e) {
            isPlay = false;
            Log.e("frost_calcurlate", e.getMessage());
        }
    }

    public void calcurlateMemberBalance(String icId, TfCardInfo info, TfMemberInfo memberInfo, TfMemberAccountRecord cashRecord, TfMemberAccountRecord subsidyRecord) {
        try {
            float cashBalance = 0, subsidyBalance = 0;
            if (cashRecord != null) {
                if (subsidyRecord == null) {
                    showMessage("", "该卡无补贴账户");
                    //   isduringPayment = false;
                    return;
                }
                if (cashRecord.getACCOUNT_STATUS().equals("1")
                        || subsidyRecord != null
                        && subsidyRecord.getACCOUNT_STATUS().equals("1")) {
                    showMessage("", "当前账户已冻结");
                    handler.sendEmptyMessage(2);
                    return;
                }
                cashBalance = Float.parseFloat(cashRecord.getBALANCE());
                subsidyBalance = Float.parseFloat(subsidyRecord != null ? subsidyRecord.getBALANCE() : "0");
                float balance = cashBalance + subsidyBalance;
//                start_time = System.currentTimeMillis();
                // 全民以及会员折扣
//                String mi_type = memberInfo.getMI_TYPE();//会员类型
//                int dis_count = MyUtil.getDisCountForMember(mi_type);//会员折扣
//                Log.e("frost", "mi_type:" + mi_type + "  会员折扣 dis_count:" + dis_count);
//                if (dis_count == 100) {
//                    dis_count = MyUtil.getDisCountForAll();//全员折扣
//                }
//                float payNum = Float.parseFloat(payMsg) * dis_count / 100f;
                float payNum = Float.parseFloat(payMsg);
                // 0 社会餐饮 先扣现金再扣补贴，1 团餐 先扣补贴再扣现金
                if (mainActivity.pStoreConfig == null) {
                    List<StoreConfig> storeConfigList = pDaoSession.queryBuilder(StoreConfig.class)
                            .build()
                            .list();
                    if (!storeConfigList.isEmpty() && storeConfigList != null) {
                        mainActivity.pStoreConfig = storeConfigList.get(0);
                    } else {
                        return;
                    }
                }

                switch (mainActivity.pStoreConfig.getSTORE_TYPE()) {
                    case "0"://社会快餐
                        cashBalance = cashBalance - payNum;
                        cashRecord.setBALANCE(MyConstant.gFormat.format(cashBalance));
                        // 现金扣完，扣补贴
                        if (cashBalance < 0) {
                            subsidyBalance = subsidyBalance - Math.abs(cashBalance);
                            cashBalance = subsidyBalance;
                            cashRecord.setBALANCE("0");
                            subsidyRecord.setBALANCE(MyConstant.gFormat.format(subsidyBalance));
                        } else {
                            // 没扣完，加上补贴金额
                            cashBalance += subsidyBalance;
                        }
                        accoutBalance = cashBalance;
                        break;
                    case "1"://团膳
                        subsidyBalance = subsidyBalance - payNum;
                        subsidyRecord.setBALANCE(MyConstant.gFormat.format(subsidyBalance));
                        if (subsidyBalance < 0) {
                            cashBalance = cashBalance - Math.abs(subsidyBalance);
                            subsidyBalance = cashBalance;
                            subsidyRecord.setBALANCE("0");
                            cashRecord.setBALANCE(MyConstant.gFormat.format(cashBalance));
                        } else {
                            subsidyBalance += cashBalance;
                        }
                        accoutBalance = subsidyBalance;
                        break;
                }
                if (accoutBalance < 0) {
//                    if (!MyUtil.obtainNetworkStatus(mContext)) {
//                        mainActivity.runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                business_balance.setText(balance + "");
//                                business_vip_name.setText(memberInfo.getMI_NAME());
//                                business_vip_no.setText(memberInfo.getMI_NO());
//                                payMsg = "";
//                                curOrderNo = "";
//                            }
//                        });
//                    }
                    // 余额不足
                    showPayStatus("余额不足");
                    playVoice(MyConstant.SP_MEDIA_MONEY_NOT_ENOUGH);
                    return;
                } else {
                    // 支付成功
                    Log.e("frost", "支付成功");
                    //折扣后金额
                    float temp_f = Float.parseFloat(MyConstant.gFormat.format(payNum));
                    // 余额
                    float temp_balance = Float.parseFloat(MyConstant.gFormat.format(accoutBalance));
                    Log.d("frost", "temp_f:" + temp_f);
                    Log.d("frost", "temp_balance:" + temp_balance);
                    showPayStatus("支付成功");
                    playVoice(MyConstant.SP_MEDIA_CONSUME_SUCCESS);
                    // TODO: 2019/11/7 创建一条消费信息
                    createConsumeInfo(temp_f, temp_balance, info.getMI_ID(), cashRecord.getACCOUNT_ID(), icId, 1 + "", 1, 1);
                    // 更新余额
//                    if (memberInfo.getMI_NAME() != null) {
//                    mainActivity.runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            business_vip_name.setText(memberInfo.getMI_NAME());
//                            business_vip_no.setText(memberInfo.getMI_NO());
//                            String balance1 = MyConstant.gFormat.format(accoutBalance);
//                            business_balance.setText(balance1);
//                            business_state.setText("支付成功");
//                            payMsg = "";
//                        }
//                    });
//                    }

                    // 修改数据库中的会员余额
                    pDaoSession.update(cashRecord);
                    pDaoSession.update(subsidyRecord);
                    return;
                }
            } else {
//                handler.sendEmptyMessage(CARD_ILLEGALITY);
                playVoice(MyConstant.SP_MEDIA_ILLEGAL_CARD);
                showPayStatus("非法卡");
            }
        } catch (Exception e) {
            Log.e("frost_calcurlate", "calcurlateMemberBalance.." + e.getMessage());
        } finally {
            cashRecord = null;
            subsidyRecord = null;
        }
    }

    // 在线更新是否启动
    private boolean onlineSync = false;
    public static String cardMemberId = "0";

    @Override
    public void onDestroy() {
        super.onDestroy();
        mTHREAD_POOL.shutdown();
    }

    public ThreadPoolExecutor mTHREAD_POOL = new ThreadPoolExecutor(6,
            14,
            1,
            TimeUnit.SECONDS,
            new LinkedBlockingDeque<Runnable>());

    /**
     * 创建一条消费记录
     */
    public void createConsumeInfo(final float totalMoney, final float balance, final String memberId, final String accountId, final String icid, final String personCount, final int CCR_STATUS, final int payWay) {
        onlineSync = true;
        mTHREAD_POOL.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    DaoSession session = MyApplication.getInstance();
                    String clientCode = MyConstant.gSharedPre.getString(MyConstant.CLIENT_CODE, "");
                    String storeCode = MyConstant.gSharedPre.getString(MyConstant.STORE_CODE, "");
                    String u_id = mainActivity.pUserInfo.getU_ID();

                    String machineNo = MyConstant.gSharedPre.getString(MyConstant.SP_MACHINE_NO, "");
                    String createTime = MyUtil.dateConversion(System.currentTimeMillis());
                    if (curOrderNo == null && curOrderNo.length() == 0) {
                        showMessage("", "订单号不能为空");
                    }
                    List<TfConsumeCardRecord> cardRecords = pDaoSession.queryBuilder(TfConsumeCardRecord.class)
                            .where(TfConsumeCardRecordDao.Properties.COR_ID.eq(curOrderNo))
                            .limit(1)
                            .build()
                            .list();
                    if (cardRecords != null && cardRecords.size() > 0) {
                        Log.e("frost", "订单号已存在");
                        Log.e("frost", "curOrderNo:" + curOrderNo);
                        return;
                    }

                    //curOrderNo = MyUtil.getPrimaryValue();
                    String orderNo = curOrderNo;
                    // 获取餐次
                    String currentTime = MyUtil.obtainCurrentSysDate(1);
                    List<TfMealTimes> mealTimeList = session.queryBuilder(TfMealTimes.class)
                            .where(TfMealTimesDao.Properties.STARTTIME.le(currentTime),
                                    TfMealTimesDao.Properties.ENDTIME.ge(currentTime))
                            .build()
                            .list();

                    TfMealTimes mealTimes;
                    if (mealTimeList.isEmpty()) {
                        mealTimes = null;
                    } else {
                        mealTimes = mealTimeList.get(0);
                    }

//                    // 会员卡消费记录
                    TfConsumeCardRecord cardRecord = new TfConsumeCardRecord();
                    cardRecord.setCCR_ID(MyUtil.getPrimaryValue());
                    cardRecord.setIC_ID(icid);
                    cardRecord.setCCR_MONEY(totalMoney);
                    Log.e("frost", "payWay:" + payWay);
                    cardRecord.setCCR_PAY_TYPE(String.valueOf(payWay));
//                    switch (payWay) {
//                        case 0:
//                            cardRecord.setCCR_PAY_TYPE("0");
//                            break;
//                        case 1:
//                            cardRecord.setCCR_PAY_TYPE("1");
//                            break;
//                        case 2:
//                            cardRecord.setCCR_PAY_TYPE("2");
//                            break;
//                        case 3:
//                            cardRecord.setCCR_PAY_TYPE("3");
//                            break;
//                        case 4:
//                            cardRecord.setCCR_PAY_TYPE("4");
//                            break;
//                    }
                    //     20/1/2
                    cardRecord.setCCR_UPLOAD_STATUS("0");
                    cardRecord.setCCR_STATUS("" + CCR_STATUS);
                    cardRecord.setACCOUNT_ID(accountId);
                    cardRecord.setCLIENT_CODE(clientCode);
                    cardRecord.setCOR_ID(orderNo);
                    cardRecord.setCREATETIME(createTime);
                    cardRecord.setISM_STATUS("0");
                    cardRecord.setMI_ID(memberId);
                    cardRecord.setMT_ID(mealTimes == null ? "" : mealTimes.getMT_ID()); // 餐次
                    cardRecord.setSTORE_CODE(storeCode);
                    cardRecord.setU_ID(u_id);
                    cardRecord.setMACHINE_NO(machineNo);
                    if (cardRecord.getMI_ID() != null && cardRecord.getMI_ID().length() > 0) {
                        cardRecord.setCCR_ORIGINALAMOUNT("" + balance);
                    }
                    cardRecord.setCCR_UPLOAD_TIME("0");
                    // 添加到流水记录中
//                    mainActivity.runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            NumberFormat ddf1 = NumberFormat.getNumberInstance();
//
//                            //设置最多保留小数位数，不足不补0。
//                            ddf1.setMaximumFractionDigits(2);
//
//                            String s = ddf1.format(totalMoney);
//                            if (s.indexOf(".") == -1) {
//                                s += ".00";
//                            }
//                            String payWay = null;
//                            if (cardRecord.getCCR_PAY_TYPE().equals("1")) {
//                                payWay = "员工卡";
//                            } else if (cardRecord.getCCR_PAY_TYPE().equals("2")) {
//                                payWay = "微信";
//                            } else if (cardRecord.getCCR_PAY_TYPE().equals("3")) {
//                                payWay = "支付宝";
//                            }
//                            weiCaiOperationWaterAdapter.insertDataToEnd(new WeiCaiWaterInfo(payWay, s));
//                        }
//                    });

                    // 消费详情
                    List<TfConsumeDetailsRecord> detailsRecordList = new ArrayList<>();

                    List<StoreConfig> list = pDaoSession.queryBuilder(StoreConfig.class).build().list();
                    String pricing = list.get(0).getPRICING();

                    TfConsumeDetailsRecord detailsRecord;
//                    OperationMenu menu = new OperationMenu();
                    detailsRecord = new TfConsumeDetailsRecord();
                    detailsRecord.setCDR_ID(getPrimaryValue());
//                    float totalPrice = menu.getTotalPrice();
//                    Log.e("frost_test","pricing:"+pricing);
//                    Log.e("frost_test","totalPrice:"+totalPrice);
//                    detailsRecord.setCDR_MONEY(MyConstant.gFormat.format(menu.getTotalPrice()));totalMoney
                    detailsRecord.setCDR_MONEY(totalMoney + "");
//                    if (menu.getId() == MyConstant.CUSTOM_FIXED_PRICE_GOODS || menu.getId() == MyConstant.CUSTOM_PRICING_GOODS) {
                    detailsRecord.setCDR_NO(pricing);
//                        Log.e("frost_test", "---1--detailsRecord.getCDR_ID():" + detailsRecord.getCDR_NO());
//                    } else {
//                        detailsRecord.setCDR_NO(String.valueOf(menu.getId()));
//                        Log.e("frost", "---2--detailsRecord.getCDR_ID():" + detailsRecord.getCDR_NO());
//                    }

                    detailsRecord.setCDR_NUMBER("1");
                    detailsRecord.setCDR_TYPE("1");
                    if ("1".equals(cardRecord.getCCR_PAY_TYPE())) {
                        detailsRecord.setCDR_UNIT_PRICE(totalMoney + "");
                    } else {
                        detailsRecord.setCDR_UNIT_PRICE(totalMoney + "");
                    }

                    detailsRecord.setCLIENT_CODE(clientCode);
                    detailsRecord.setCOR_ID(orderNo);
                    detailsRecord.setCREATETIME(createTime);
                    detailsRecord.setISM_STATUS("0");
                    detailsRecord.setSTORE_CODE(storeCode);
                    detailsRecordList.add(detailsRecord);

                    // 消费订单
                    TfConsumeOrderRecord orderRecord = new TfConsumeOrderRecord();
                    orderRecord.setCLIENT_CODE(clientCode);
                    orderRecord.setCOR_AMOUNT(totalMoney + "");
                    orderRecord.setCOR_ID(orderNo);
                    orderRecord.setCOR_TYPE("0");
                    orderRecord.setCREATETIME(createTime);
                    orderRecord.setISM_STATUS("0");
                    orderRecord.setSTORE_CODE(storeCode);
                    orderRecord.setMACHINE_NO(machineNo);
                    orderRecord.setUPDATETIME(MyUtil.dateConversion(System.currentTimeMillis()));

                    if (!MyUtil.obtainNetworkStatus(mContext) || payWay != 1) {
                        onlineSync = false;
                        Log.d("frost", "saveOrder: saveOrder");
                        saveOrder(cardRecord, detailsRecordList, orderRecord);
                    } else {
                        // 更新
                        try {
                            Log.d("frost", "updateToServerOnline:  ");
                            Log.d("frost", "updateToServerOnline: updateToServerOnline");
                            updateToServerOnline(cardRecord, detailsRecordList, orderRecord);
                        } catch (Exception e) {
                            Log.d("frost", "updateToServerOnline: Exception");
                            Log.d("frost", "updateToServerOnline: e:" + e.getMessage());
                            onlineSync = false;
                            saveOrder(cardRecord, detailsRecordList, orderRecord);
                        }
                    }
                } catch (Exception e) {
                    onlineSync = false;
                    e.printStackTrace();
                    Log.e("frost", e.toString());
                }
            }
        });
    }

    /**
     * 将本地记录的消费信息发送到服务器（更新）
     * 离线模式
     *
     * @throws JSONException
     */
    public void updateToServerOnline(final TfConsumeCardRecord cardRecord,
                                     final List<TfConsumeDetailsRecord> detailsRecordList,
                                     final TfConsumeOrderRecord orderRecord) {
        Gson gson = new Gson();
        OnlineUpdateResultInfo syncInfo = new OnlineUpdateResultInfo();
        List<OnlineUpdateResultInfo.TfConsumeDetailsRecordBean> details = new ArrayList<>();
        OnlineUpdateResultInfo.TfConsumeOrderRecordBean orderBean = null;
        OnlineUpdateResultInfo.TfConsumeDetailsRecordBean detailsBean;
        OnlineUpdateResultInfo.TfConsumeCardRecordBean cardBean = null;

        orderBean = new OnlineUpdateResultInfo.TfConsumeOrderRecordBean();
        orderBean.setCOR_ID(orderRecord.getCOR_ID());
        orderBean.setCOR_MONERY(orderRecord.getCOR_AMOUNT());
        orderBean.setCOR_AMOUNT(orderRecord.getCOR_AMOUNT());
        if (orderRecord.getMACHINE_NO() == null) {
            orderBean.setMACHINE_NO("0");
        } else {
            orderBean.setMACHINE_NO(orderRecord.getMACHINE_NO());
        }
        orderBean.setISM_STATUS(orderRecord.getISM_STATUS());
        orderBean.setSTORE_CODE(orderRecord.getSTORE_CODE());
        orderBean.setCREATETIME(orderRecord.getCREATETIME());
        orderBean.setCOR_TYPE(orderRecord.getCOR_TYPE());
        orderBean.setADDR_ID(String.valueOf(orderRecord.getADDR_ID()));
        orderBean.setCLIENT_CODE(orderRecord.getCLIENT_CODE());
        orderBean.setUPDATETIME(orderRecord.getUPDATETIME());

        // 添加到列表就表示能同步了，修改同步状态

        for (TfConsumeDetailsRecord detailsRecord : detailsRecordList) {
            detailsBean = new OnlineUpdateResultInfo.TfConsumeDetailsRecordBean();
            detailsBean.setCOR_ID(detailsRecord.getCOR_ID());
            detailsBean.setCDR_UNIT_PRICE(detailsRecord.getCDR_UNIT_PRICE());
            detailsBean.setCDR_MONEY(detailsRecord.getCDR_MONEY());
            detailsBean.setCDR_NO(detailsRecord.getCDR_NO());
            detailsBean.setCDR_TYPE(detailsRecord.getCDR_TYPE());
            detailsBean.setISM_STATUS(detailsRecord.getISM_STATUS());
            detailsBean.setSTORE_CODE(detailsRecord.getSTORE_CODE());
            detailsBean.setCREATETIME(detailsRecord.getCREATETIME());
            detailsBean.setCDR_NUMBER(detailsRecord.getCDR_NUMBER());
            detailsBean.setCLIENT_CODE(detailsRecord.getCLIENT_CODE());
            detailsBean.setCDR_ID(detailsRecord.getCDR_ID());
            details.add(detailsBean);
        }
        //
        cardBean = new OnlineUpdateResultInfo.TfConsumeCardRecordBean();
        cardBean.setCOR_ID(cardRecord.getCOR_ID());
        cardBean.setCCR_MONEY(String.valueOf(cardRecord.getCCR_MONEY()));
        if (cardRecord.getMI_ID() == null) {
            cardBean.setMI_ID("0");
        } else {
            cardBean.setMI_ID(cardRecord.getMI_ID());
        }
        cardBean.setMT_ID(cardRecord.getMT_ID());

        if (cardRecord.getMACHINE_NO() == null) {
            cardBean.setMACHINE_NO("0");
        } else {
            cardBean.setMACHINE_NO(cardRecord.getMACHINE_NO());
        }
        cardBean.setCCR_ID(cardRecord.getCCR_ID());
        cardBean.setISM_STATUS(cardRecord.getISM_STATUS());
        cardBean.setSTORE_CODE(cardRecord.getSTORE_CODE());
        cardBean.setCREATETIME(cardRecord.getCREATETIME());
        cardBean.setCLIENT_CODE(cardRecord.getCLIENT_CODE());
        cardBean.setCCR_PAY_TYPE(cardRecord.getCCR_PAY_TYPE());
        cardBean.setCCR_STATUS(cardRecord.getCCR_STATUS());
        cardBean.setIC_ID(cardRecord.getIC_ID());
        cardBean.setPAY_REMARK("手持机");


        if (cardRecord.getMI_ID() != null && cardRecord.getMI_ID().length() > 0) {
            cardBean.setCCR_ORIGINALAMOUNT(cardRecord.getCCR_ORIGINALAMOUNT());
        }
        cardBean.setU_ID(cardRecord.getU_ID());
        String uploadTime = MyUtil.dateConversion(System.currentTimeMillis());
        cardBean.setCCR_UPLOAD_TIME(uploadTime);


        syncInfo.setTf_consume_order_record(orderBean);
        syncInfo.setTf_consume_details_record(details);
        syncInfo.setTf_consume_card_record(cardBean);
        final String data = gson.toJson(syncInfo, OnlineUpdateResultInfo.class);
        Log.d("pay", "updateToServerOnline: " + data);
        String ip = MyConstant.gSharedPre.getString(MyConstant.SP_Server_IP,"");
        String port = MyConstant.gSharedPre.getString(MyConstant.SP_Server_PORT,"");

        String url = "http://" + ip + ":" + port+"/k-occ/consume/onlinehand";
        RequestBody requestBody = new FormBody.Builder().add("data",data).build();
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10,TimeUnit.SECONDS)
                .readTimeout(1,TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                try {
                    payMsg = "";
                    isPlay = false;
                    if (e instanceof SocketTimeoutException) {
                        showPayStatus("支付成功");
                        playVoice(MyConstant.SP_MEDIA_CONSUME_SUCCESS);
                        cardRecord.setISM_STATUS("1");
                        Log.e("frost", "SocketTimeoutException");
                    }
                    if (e instanceof ConnectException) {
                        Log.e("frost", "ConnectException");
                        showPayStatus("支付错误，请重试");
                        onlineSync = false;
                    }
                    saveOrder(cardRecord, detailsRecordList, orderRecord);
                    Log.d(TAG, "在线状态更新 onError: " + e.getMessage());
                }catch (Exception e1){
                    Log.e("frost",e1.getMessage());
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                showPayStatus("支付成功");
                playVoice(MyConstant.SP_MEDIA_CONSUME_SUCCESS);
                payMsg = "";
                isPlay = false;
                onlineSync = false;
                try {
                    Log.e("url", "updateToServerOnline:777 onNext");
                    String body = response.body().string();
                    Log.e("frost", body);
                    UpdateResultInfo updateResultInfo = gson.fromJson(body, UpdateResultInfo.class);
                    if (updateResultInfo != null && updateResultInfo.isResult()) {
                        cardRecord.setISM_STATUS("1");
                    }
                    saveOrder(cardRecord, detailsRecordList, orderRecord);
                }catch (Exception e){
                    Log.e("frost_update",e.getMessage());
                }
            }
        });
//        LocalRetrofit.createService().postUpdateOnline(data)
//                .subscribeOn(Schedulers.io())
//                .subscribe(new Observer<UpdateResultInfo>() {
//                    @Override
//                    public void onCompleted() {
//                        onlineSync = false;
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//
//                        //cardRecord.setCCR_UPLOAD_STATUS("2");
//                        //pDaoSession.update(cardRecord);
//                    }
//
//                    @Override
//                    public void onNext(UpdateResultInfo syncResultInfo) {
//                    }
//                });

    }

    public void saveOrder(final TfConsumeCardRecord cardRecord,
                          final List<TfConsumeDetailsRecord> detailsRecordList,
                          final TfConsumeOrderRecord orderRecord) {
        if (cardRecord != null) {
            DaoSession session = MyApplication.getInstance();
            session.insert(cardRecord);

            if (detailsRecordList != null) {
                for (TfConsumeDetailsRecord detailsRecord : detailsRecordList) {
                    if (detailsRecord != null) {
                        session.insert(detailsRecord);
                    }
                }
            }

            if (orderRecord != null) {
                session.insert(orderRecord);
            }
        }
    }

    private void showPayStatus(String payStatus) {
        mainActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                bus_status.setText(payStatus);
            }
        });
    }

    /**
     * 音频播放
     *
     * @param type
     */
    public void playVoice(int type) {
        int resId = 0;
        switch (type) {
            case MyConstant.SP_MEDIA_CONSUME_SUCCESS:
                resId = R.raw.consumesuccess;
                break;
            case MyConstant.SP_MEDIA_MONEY_NOT_ENOUGH:
                resId = R.raw.moneynotenough;
                break;
            case MyConstant.SP_MEDIA_PLEASE_SET_CARD:
                resId = R.raw.pleasesetcard;
                break;
            case MyConstant.SP_MEDIA_NO_EFFECT_CARD:
                resId = R.raw.noeffectcard;
                break;
            case MyConstant.SP_MEDIA_ILLEGAL_CARD:
                resId = R.raw.illegalcard;
                break;
            case MyConstant.SP_CANCEL_CARD:
                // 注销卡
                resId = R.raw.canclecard;
                break;
            case MyConstant.SP_LOST_CARD:
                // 挂失
                resId = R.raw.lostcard;
                break;

        }
        try {
            mPlayer = MediaPlayer.create(mContext, resId);
            //FIXME: mPlayer is null if wav is mono(only support stereo)
            if (mPlayer != null) {
                mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        if (mp.isPlaying()) {
                            mp.stop();
                        }
                        mp.release();
                        mp = null;
                        //支付成功-----发送 refresh 命令
                        if (type == MyConstant.SP_MEDIA_CONSUME_SUCCESS) {
                            if (fixed_price_status) {
                                settlement();
                            }
                        }
                    }
                });
                mPlayer.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initview() {
        fixed_price_status = MyConstant.gSharedPre.getBoolean(MyConstant.FIXED_PRICE_STATUS, false);
        bus_num0 = (Button) findViewById(R.id.bus_num0);
        bus_num1 = (Button) findViewById(R.id.bus_num1);
        bus_num2 = (Button) findViewById(R.id.bus_num2);
        bus_num3 = (Button) findViewById(R.id.bus_num3);
        bus_num4 = (Button) findViewById(R.id.bus_num4);
        bus_num5 = (Button) findViewById(R.id.bus_num5);
        bus_num6 = (Button) findViewById(R.id.bus_num6);
        bus_num7 = (Button) findViewById(R.id.bus_num7);
        bus_num8 = (Button) findViewById(R.id.bus_num8);
        bus_num9 = (Button) findViewById(R.id.bus_num9);
        bus_num_dot = (Button) findViewById(R.id.bus_num_dot);
        bus_refresh = (ImageButton) findViewById(R.id.bus_refresh);
        bus_scan = (ImageButton) findViewById(R.id.bus_scan);
        bus_enter = (ImageButton) findViewById(R.id.bus_enter);
        bus_status = (TextView) findViewById(R.id.bus_status);
        bus_money = (TextView) findViewById(R.id.bus_money);
        bus_put_price = (EditText) findViewById(R.id.bus_put_price);
        bus_put_price.setInputType(InputType.TYPE_NULL);
        bus_put_price.requestFocus();
        bus_num0.setOnClickListener(this);
        bus_num1.setOnClickListener(this);
        bus_num2.setOnClickListener(this);
        bus_num3.setOnClickListener(this);
        bus_num4.setOnClickListener(this);
        bus_num5.setOnClickListener(this);
        bus_num6.setOnClickListener(this);
        bus_num7.setOnClickListener(this);
        bus_num8.setOnClickListener(this);
        bus_num9.setOnClickListener(this);
        bus_num_dot.setOnClickListener(this);
        bus_refresh.setOnClickListener(this);
        bus_scan.setOnClickListener(this);
        bus_enter.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bus_num0:
                inputEdit("0");
                break;
            case R.id.bus_num1:
                inputEdit("1");
                break;
            case R.id.bus_num2:
                inputEdit("2");
                break;
            case R.id.bus_num3:
                inputEdit("3");
                break;
            case R.id.bus_num4:
                inputEdit("4");
                break;
            case R.id.bus_num5:
                inputEdit("5");
                break;
            case R.id.bus_num6:
                inputEdit("6");
                break;
            case R.id.bus_num7:
                inputEdit("7");
                break;
            case R.id.bus_num8:
                inputEdit("8");
                break;
            case R.id.bus_num9:
                inputEdit("9");
                break;
            case R.id.bus_num_dot:
                inputEdit(".");
                break;
            case R.id.bus_scan:
                if (TextUtils.isEmpty(payMsg)) {
                    return;
                }
                goScan();
                break;
            case R.id.bus_refresh:
                refresh();
                break;
            case R.id.bus_enter:
                settlement();
                break;
        }
    }


    private void refresh() {
        mainActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isPlay) {
                    return;
                }
                bus_put_price.setText("");
                bus_money.setText("0");
                bus_status.setText("准备下单");
                payMsg = "";
                curOrderNo = "";
            }
        });
    }

    private void settlement() {
        if (isPlay) {
            return;
        }
        handler.sendEmptyMessage(SETTLEMENT);
    }

    private void inputEdit(String content) {
        if (bus_put_price != null) {
            bus_put_price.requestFocus();
            int index = bus_put_price.getSelectionStart();
            Editable editable = bus_put_price.getText();
            editable.insert(index, content);
            String curContent[] = editable.toString().split("\\.");
            if (curContent.length >= 2) {
                if (curContent[1].length() >= 2) {
                    Log.d("frost", "length error");
                    return;
                }
            }
            bus_put_price.setText(editable.toString());
            bus_put_price.setSelection(index + content.length());
        }
    }
}
